﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArithmeticExpressionCalculator
{
    public class DifficultExpression : DoubleSideExpression, IExpressionCalculator
    {
        private int GetAddOrSubOperationPosition(string expr, char[] symbols)
        {
            int position;
            char[] array = new char[expr.Length - 1];
            expr.CopyTo(1, array, 0, expr.Length - 1);
            string buf = new string(array);
            position = buf.IndexOfAny(symbols);
            if (position != -1) position++;
            return position;
        }
        public double Execute(string str)
        {
            char[] first_priority = { '*', '/' };
            int mul_div_position = str.IndexOfAny(first_priority);
            while (mul_div_position != -1)
            {
                str = base.CalculateOperationByPosition(str, mul_div_position);
                mul_div_position = str.IndexOfAny(first_priority);
            }
            char[] second_priority = { '+', '-' };
            int add_sub_position = str.IndexOfAny(second_priority);
            if (add_sub_position == 0)
            {
                add_sub_position = GetAddOrSubOperationPosition(str, second_priority);
            }
            while (add_sub_position != -1)
            {
                str = base.CalculateOperationByPosition(str, add_sub_position);

                add_sub_position = str.IndexOfAny(second_priority);
                if (add_sub_position == 0)
                {
                    add_sub_position = GetAddOrSubOperationPosition(str, second_priority);
                }
            }
            return Convert.ToDouble(str);
        }
    }
}
